package cn.jw.starter.redis.core.api;

import java.util.concurrent.TimeUnit;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * redis分布式锁
 *
 * @author wuyuanchun
 * @since 2024/4/29 14:30
 */
public class RedisLockService {
    private Logger logger = LoggerFactory.getLogger(RedisLockService.class);
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 添加redis分布式锁，如果出现竞争，会等待30秒，如果30秒内还是获取不到锁，则返回false
     *
     * @param lockKey
     * @param task
     */
    public boolean tryLock(String lockKey, Runnable task) {
        return tryLock(lockKey, task, 30);
    }

    /**
     * 获取一个锁，并指定超时时间
     *
     * @param lockKey
     * @param task
     * @param timeoutSecond
     *     超时时间，单位秒
     * @return
     */
    public boolean tryLock(String lockKey, Runnable task, int timeoutSecond) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            logger.debug("开始添加分布式锁,key= {}", lockKey);
            boolean result = lock.tryLock(timeoutSecond, TimeUnit.SECONDS);
            if (result) {
                task.run();
            }
            return result;
        } catch (Throwable e) {
            logger.error("添加分布式销锁异常");
            throw new RuntimeException(e);
        } finally {
            if (lock!=null) {
                lock.unlock();
                logger.debug("分布式锁解除成功,key= {}", lockKey);
            }
        }
    }
}
